package icu.twtool.ui.router.routes

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import icu.twtool.database.mapper.ExerciseMeteDataMapper
import icu.twtool.database.model.ExerciseMetaData
import icu.twtool.ui.component.PagingBar
import icu.twtool.ui.component.PagingState
import icu.twtool.ui.component.PrimaryButton
import icu.twtool.ui.component.rememberPagingState
import icu.twtool.ui.router.Route
import icu.twtool.ui.router.routes.exercise.AddExerciseDialog
import icu.twtool.ui.router.routes.exercise.ExerciseTable

/**
 * 习题管理视图
 * @author Wen
 * @since 2022-11-02
 */
@Composable
@Suppress("FunctionName")
fun ExerciseManage() {
    var add by remember { mutableStateOf(false) }
    val pagingState = rememberPagingState<ExerciseMetaData>(1, 1)
    LaunchedEffect(pagingState) {
        refreshState(pagingState)
    }
    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Row(Modifier.padding(16.dp)) {
            PrimaryButton("添加习题") {
                add = true
            }
        }
        ExerciseTable(pagingState.data) {
            refreshState(pagingState)
        }
        Spacer(Modifier.weight(1f))
        PagingBar(
            pagingState,
            modifier = Modifier.align(Alignment.CenterHorizontally)
        ) {
            refreshState(pagingState)
        }
    }
    if (add) {
        AddExerciseDialog(
            onCloseRequest = {
                add = false
            },
            onComplete = {
                add = false
                refreshState(pagingState)
            }
        )
    }
}

/**
 * 习题管理路由
 */
val exerciseManageRoute = Route("习题管理") {
    ExerciseManage()
}

/**
 * 刷新习题元数据
 */
private fun refreshState(state: PagingState<ExerciseMetaData>) {
    state.max = ExerciseMeteDataMapper.count() / state.size + 1
    state.data = ExerciseMeteDataMapper.selectPage((state.page - 1) * state.size, state.size)
}